package special.graph;

public class Solution547 {
    int[] father;

    public int findCircleNum(int[][] isConnected) {
        father = new int[isConnected.length];
        for (int i = 0; i < isConnected.length; i++) {
            father[i] = i;
        }
        for (int i = 0; i < isConnected.length; i++) {
            for (int j = i + 1; j < isConnected[i].length; j++) {
                if (isConnected[i][j] == 1) join(i, j);
            }
        }
        int res = 0;
        for (int i = 0; i < father.length; i++) {
            if (father[i] == i) res++;
        }
        return res;
    }

    public int find(int x) {
        if (x == father[x]) return x;
        father[x] = find(father[x]);
        return father[x];
    }

    public boolean same(int x, int y) {
        x = find(x);
        y = find(y);
        return x == y;
    }

    public void join(int x, int y) {
        x = find(x);
        y = find(y);
        if (x == y) return;
        father[y] = x;
    }
}
